<template>
	<view class="hospital-list">
		<!-- 搜索栏 -->
		<view class="search-bar">
			<view class="search-input">
				<view class="search-input-box">
					<view class="search-icon-wrap">
						<image class="search-icon" src="/static/icons/search.png" mode="aspectFit"></image>
					</view>
					<input
						type="text"
						v-model="searchKeyword"
						placeholder="搜索医院名称"
						placeholder-class="placeholder"
						@input="onSearchInput"
						confirm-type="search"
						@confirm="onSearchConfirm"
					/>
					<view v-if="searchKeyword" class="clear-icon" @tap="clearSearch">
						<text class="clear-text">✕</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 筛选条件 -->
		<view class="filter-bar">
			<picker :range="provinceNames" @change="onProvinceChange">
				<view class="filter-item">
					<text>{{selectedProvince || '省'}}</text>
					<u-icon name="arrow-down" size="14"></u-icon>
				</view>
			</picker>
			
			<picker :range="cityNames" @change="onCityChange" :disabled="!selectedProvince">
				<view class="filter-item" :class="{'filter-item-disabled': !selectedProvince}">
					<text>{{selectedCity || '市'}}</text>
					<u-icon name="arrow-down" size="14"></u-icon>
				</view>
			</picker>
			
			<picker :range="districtNames" @change="onDistrictChange" :disabled="!selectedCity">
				<view class="filter-item" :class="{'filter-item-disabled': !selectedCity}">
					<text>{{selectedDistrict || '区'}}</text>
					<u-icon name="arrow-down" size="14"></u-icon>
				</view>
			</picker>
			
			<!-- <picker :range="departments" @change="onDepartmentChange">
				<view class="filter-item">
					<text>{{selectedDepartment || '科室'}}</text>
					<u-icon name="arrow-down" size="14"></u-icon>
				</view>
			</picker> -->
		</view>
		
		<!-- 医院列表 -->
		<scroll-view scroll-y class="hospital-scroll">
			<view class="hospital-item" v-for="(item, index) in hospitalList" :key="index" @click="goToDetail(item)">
				<image class="hospital-image" :src="item.imgurl" mode="aspectFill"></image>
				<view class="hospital-info">
					<view class="hospital-name">{{item.name}}</view>
					<view class="hospital-address">{{item.address}}</view>
					<view class="hospital-tags">
						<text class="tag" v-for="(tag, tagIndex) in item.tags" :key="tagIndex">{{tag}}</text>
					</view>
					<view class="hospital-time">周一至周日 08:00-18:00</view>
				</view>
				<view class="hospital-actions">
					<button class="map-btn" @tap.stop="showHospitalLocation(item, $event)">查看地图</button>
					<button class="map-btn" @tap.stop="goTo3D(item)">3D视图</button>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			searchKeyword: '',
			selectedProvince: '',
			selectedCity: '',
			selectedDistrict: '',
			selectedDepartment: '',
			// 省市区数据
			provinces: [],
			cities: [],
			districts: [],
			// 科室数据
			departments: [],
			// 原始医院列表数据
			originalHospitalList: [],
			// 显示的医院列表
			hospitalList: []
		}
	},
	computed: {
		// 将对象数组转换为名称数组，用于选择器显示
		provinceNames() {
			return ['全部', ...this.provinces.map(item => item.name)];
		},
		cityNames() {
			return ['全部', ...this.cities.map(item => item.name)];
		},
		districtNames() {
			return ['全部', ...this.districts.map(item => item.name)];
		}
	},
	onLoad() {
		// 页面加载时获取省份列表
		this.getProvinceList();
		// 获取科室列表
		this.getDepartmentList();
		// 获取医院列表
		this.getHospitalList();
	},
	methods: {
		clearSearch() {
			this.searchKeyword = '';
			this.hospitalList = [...this.originalHospitalList];
		},
		
		onSearchInput(e) {
			const value = e.detail.value;
			this.searchKeyword = value;
			this.doSearch(value);
		},
		
		onSearchConfirm(e) {
			const value = e.detail.value;
			this.doSearch(value);
		},
		
		doSearch(value) {
			if (!value || value.trim() === '') {
				this.hospitalList = [...this.originalHospitalList];
				return;
			}
			
			const keyword = value.trim();
			// 只搜索医院名称
			this.hospitalList = this.originalHospitalList.filter(item => {
				if (!item || !item.name) return false;
				return item.name.toLowerCase().includes(keyword.toLowerCase());
			});
			
			// 如果没有找到完全匹配的，尝试拼音匹配（如果需要的话可以添加拼音匹配逻辑）
			if (this.hospitalList.length === 0) {
				console.log('没有找到完全匹配的医院');
			}
		},
		
		// 省份选择变更
		onProvinceChange(e) {
			const index = e.detail.value;
			const provinceName = this.provinceNames[index];
			
			if (provinceName === '全部') {
				this.selectedProvince = '';
				this.selectedCity = '';
				this.selectedDistrict = '';
				this.cities = [];
				this.districts = [];
				// 重置为原始医院列表
				this.hospitalList = [...this.originalHospitalList];
				return;
			}
			
			const province = this.provinces[index - 1]; // 因为添加了"全部"选项，所以索引需要减1
			this.selectedProvince = province.name;
			
			// 清空城市和区域选择
			this.selectedCity = '';
			this.selectedDistrict = '';
			
			// 获取对应城市列表
			this.getCityList(province.id);
			
			// 筛选医院
			this.filterHospitals();
		},
		
		// 城市选择变更
		onCityChange(e) {
			const index = e.detail.value;
			const cityName = this.cityNames[index];
			
			if (cityName === '全部') {
				this.selectedCity = '';
				this.selectedDistrict = '';
				this.districts = [];
				// 只按省份筛选
				this.filterHospitals();
				return;
			}
			
			const city = this.cities[index - 1]; // 因为添加了"全部"选项，所以索引需要减1
			this.selectedCity = city.name;
			
			// 清空区域选择
			this.selectedDistrict = '';
			
			// 获取对应区域列表
			this.getDistrictList(city.id);
			
			// 筛选医院
			this.filterHospitals();
		},
		
		// 区域选择变更
		onDistrictChange(e) {
			const index = e.detail.value;
			const districtName = this.districtNames[index];
			
			if (districtName === '全部') {
				this.selectedDistrict = '';
				// 只按省市筛选
				this.filterHospitals();
				return;
			}
			
			this.selectedDistrict = this.districts[index - 1].name; // 因为添加了"全部"选项，所以索引需要减1
			
			// 筛选医院
			this.filterHospitals();
		},
		
		// 科室选择变更
		onDepartmentChange(e) {
			const index = e.detail.value;
			this.selectedDepartment = this.departments[index];
			
			// 筛选医院
			this.filterHospitals();
		},
		
		filterHospitals() {
			// 根据选择的条件筛选医院列表
			console.log('筛选条件:', {
				province: this.selectedProvince,
				city: this.selectedCity,
				district: this.selectedDistrict,
				department: this.selectedDepartment
			});
			
			// 构建查询参数
			const params = {
				currentPage: 1,
				pageSize: 10
			};
			if (this.selectedProvince) params.province = this.selectedProvince;
			if (this.selectedCity) params.city = this.selectedCity;
			if (this.selectedDistrict) params.district = this.selectedDistrict;
			if (this.selectedDepartment) params.department = this.selectedDepartment;
			
			uni.request({
				url: 'http://localhost:8090/hospital/list',
				method: 'POST',
				data: params,
				success: (res) => {
					console.log('筛选医院列表成功:', res);
					if (res.statusCode === 200 && res.code === 200) {
						const hospitals = res.data;
						// 获取所有医院的地址信息
						const addressIds = hospitals.map(hospital => hospital.addressId);
						this.getAddressesByIds(addressIds, hospitals);
					} else {
						// 如果接口不存在或失败，使用本地筛选
						this.localFilterHospitals();
						// uni.showToast({
						// 	// title: '使用本地筛选',
						// 	// icon: 'none'
						// });
					}
				},
				fail: (err) => {
					console.error('筛选医院列表请求失败:', err);
					// 接口调用失败时，使用本地筛选
					this.localFilterHospitals();
					uni.showToast({
						title: '网络请求失败，使用本地筛选',
						icon: 'none'
					});
				}
			});
		},
		
		// 本地筛选（备用方案）
		localFilterHospitals() {
			// 先重置为原始列表
			let filteredList = [...this.originalHospitalList];
			
			// 按条件筛选
			if (this.selectedProvince) {
				filteredList = filteredList.filter(item => 
					item.address && item.address.includes(this.selectedProvince));
			}
			
			if (this.selectedCity) {
				filteredList = filteredList.filter(item => 
					item.address && item.address.includes(this.selectedCity));
			}
			
			if (this.selectedDistrict) {
				filteredList = filteredList.filter(item => 
					item.address && item.address.includes(this.selectedDistrict));
			}
			
			if (this.selectedDepartment) {
				// 假设医院有departments字段表示科室
				filteredList = filteredList.filter(item => 
					item.departments && item.departments.includes(this.selectedDepartment));
			}
			
			// 更新显示的医院列表
			this.hospitalList = filteredList;
		},
		
		// 跳转到医院详情页
		goToDetail(hospital) {
			console.log('跳转到医院详情页:', hospital)
			uni.navigateTo({
				url: `/pages/hospital/detail?id=${hospital.id}`,
				success: () => {
					console.log('跳转成功')
				},
				fail: (err) => {
					console.error('跳转失败:', err)
					uni.showToast({
						title: '页面跳转失败',
						icon: 'none'
					})
				}
			})
		},
		
		// 显示医院位置
		showHospitalLocation(hospital, event) {
			// 阻止点击事件冒泡
			event.stopPropagation();
			
			// 在控制台输出医院信息
			console.log('医院位置信息:', {
				医院名称: hospital.name,
				医院地址: hospital.address,
				经度: hospital.longitude,
				纬度: hospital.latitude,
				完整信息: hospital
			})

			if (!hospital.latitude || !hospital.longitude) {
				uni.showToast({
					title: '医院位置信息不完整',
					icon: 'none'
				})
				return
			}

			uni.openLocation({
				latitude: Number(hospital.latitude),
				longitude: Number(hospital.longitude),
				name: hospital.name,
				address: hospital.address,
				showLocation: false,
				success: () => {
					console.log('打开地图成功')
				},
				fail: (err) => {
					console.error('打开地图失败:', err)
					uni.showToast({
						title: '打开地图失败',
						icon: 'none'
					})
				}
			})
		},
		
		// 跳转到3D视图
		goTo3D(hospital) {
			console.log('跳转到3D视图:', hospital)
			uni.navigateTo({
				url: `/pages/hospital/3d?id=${hospital.id}`,
				success: () => {
					console.log('跳转到3D视图成功')
				},
				fail: (err) => {
					console.error('跳转到3D视图失败:', err)
					uni.showToast({
						title: '页面跳转失败',
						icon: 'none'
					})
				}
			})
		},
		
		// 获取省份列表
		getProvinceList() {
			console.log('开始获取省份列表');
			
			// 使用真实API
			uni.request({
				url: 'http://localhost:8090/province/findProvinces',
				method: 'GET',
				success: (res) => {
					console.log('获取省份列表成功:', res);
					if (res.statusCode === 200 && res.data.code === 200) {
						this.provinces = res.data.data;
						console.log('设置后的省份列表:', this.provinces);
					} else {
						uni.showToast({
							title: res.data.msg || '获取省份列表失败',
							icon: 'none'
						});
					}
				},
				fail: (err) => {
					console.error('获取省份列表请求失败:', err);
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					});
				}
			});
		},
		
		// 获取城市列表
		getCityList(provinceId) {
			// 根据省份ID获取对应的城市列表
			console.log('获取城市列表, provinceId:', provinceId);
			
			uni.request({
				url: `http://localhost:8090/city/findCity`,
				method: 'GET',
				data: { provinceId: provinceId },
				success: (res) => {
					console.log('获取城市列表成功:', res);
					if (res.statusCode === 200 && res.data.code === 200) {
						this.cities = res.data.data;
						console.log('设置城市列表:', this.cities);
					} else {
						uni.showToast({
							title: res.data.msg || '获取城市列表失败',
							icon: 'none'
						});
					}
				},
				fail: (err) => {
					console.error('获取城市列表请求失败:', err);
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					});
				}
			});
		},
		
		// 获取区域列表
		getDistrictList(cityId) {
			// 根据城市ID获取对应的区域列表
			console.log('获取区域列表, cityId:', cityId);
			
			uni.request({
				url: `http://localhost:8090/district/findDistrict`,
				method: 'GET',
				data: { cityId: cityId },
				success: (res) => {
					console.log('获取区域列表成功:', res);
					if (res.statusCode === 200 && res.data.code === 200) {
						this.districts = res.data.data;
						console.log('设置区域列表:', this.districts);
					} else {
						uni.showToast({
							title: res.data.msg || '获取区域列表失败',
							icon: 'none'
						});
					}
				},
				fail: (err) => {
					console.error('获取区域列表请求失败:', err);
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					});
				}
			});
		},
		
		// 重置筛选条件
		resetFilters() {
			this.selectedProvince = '';
			this.selectedCity = '';
			this.selectedDistrict = '';
			this.selectedDepartment = '';
			this.cities = [];
			this.districts = [];
			// 重置医院列表
			this.hospitalList = [...this.originalHospitalList];
		},
		
		// 获取科室列表
		getDepartmentList() {
			console.log('开始获取科室列表');
			
			uni.request({
				url: 'http://localhost:8090/dep/findBigDeps',
				method: 'GET',
				success: (res) => {
					console.log('获取科室列表成功:', res);
					if (res.statusCode === 200 && res.data.code === 200) {
						this.departments = res.data.data.map(item => item.name);
						console.log('设置后的科室列表:', this.departments);
					} else {
						uni.showToast({
							title: res.data.msg || '获取科室列表失败',
							icon: 'none'
						});
					}
				},
				fail: (err) => {
					console.error('获取科室列表请求失败:', err);
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					});
				}
			});
		},
		
		// 获取医院列表
		getHospitalList() {
			console.log('开始获取医院列表');
			
			uni.request({
				url: 'http://localhost:8090/hospital/findHospitals',
				method: 'GET',
				success: (res) => {
					console.log('获取医院列表成功:', res);
					if (res.statusCode === 200 && res.data.code === 200) {
						const hospitals = res.data.data;
						// 获取所有医院的地址信息
						const addressIds = hospitals.map(hospital => hospital.addressId);
						this.getAddressesByIds(addressIds, hospitals);
					} else {
						uni.showToast({
							title: res.data.msg || '获取医院列表失败',
							icon: 'none'
						});
					}
				},
				fail: (err) => {
					console.error('获取医院列表请求失败:', err);
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					});
				}
			});
		},
		
		// 根据ID批量获取地址信息
		getAddressesByIds(addressIds, hospitals) {
			console.log('开始获取地址信息, addressIds:', addressIds);
			
			// 使用Promise.all并发获取所有地址信息
			const addressPromises = addressIds.map(id => {
				return new Promise((resolve, reject) => {
					uni.request({
						url: `http://localhost:8090/address/${id}`,
						method: 'GET',
						success: (res) => {
							if (res.statusCode === 200 && res.data.code === 200) {
								resolve(res.data.data);
							} else {
								resolve(null); // 如果获取失败返回null
							}
						},
						fail: (err) => {
							console.error(`获取地址ID ${id} 失败:`, err);
							resolve(null);
						}
					});
				});
			});
			
			Promise.all(addressPromises).then(addresses => {
				// 将地址信息关联到医院数据中
				const hospitalsWithAddress = hospitals.map(hospital => {
					const address = addresses.find(addr => addr && addr.id === hospital.addressId);
					return {
						...hospital,
						address: address ? `${address.province}${address.city}${address.district}${address.detailedAddress}` : '地址未知'
					};
				});
				
				this.originalHospitalList = hospitalsWithAddress;
				this.hospitalList = [...this.originalHospitalList];
				console.log('设置后的医院列表:', this.hospitalList);
			}).catch(err => {
				console.error('获取地址信息失败:', err);
				uni.showToast({
					title: '获取地址信息失败',
					icon: 'none'
				});
			});
		},
	}
}
</script>

<style lang="scss" scoped>
.hospital-list {
	min-height: 100vh;
	background-color: #f5f5f5;
	
	.search-bar {
		background: linear-gradient(135deg, #4CD964, #39b54a);
		padding: 16rpx 30rpx;
		position: sticky;
		top: 0;
		z-index: 100;
		
		.search-input {
			background-color: rgba(255, 255, 255, 0.98);
			border-radius: 32rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
			transition: all 0.3s ease;
			
			&:hover {
				box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.15);
			}
			
			.search-input-box {
				display: flex;
				align-items: center;
				padding: 8rpx 20rpx;
				
				.search-icon-wrap {
					display: flex;
					align-items: center;
					justify-content: center;
					width: 36rpx;
					height: 36rpx;
					margin-right: 12rpx;
					
					.search-icon {
						width: 28rpx;
						height: 28rpx;
						opacity: 0.7;
					}
				}
				
				input {
					flex: 1;
					height: 52rpx;
					font-size: 26rpx;
					color: #333;
					padding: 0 8rpx;
				}
				
				.placeholder {
					color: #bbb;
					font-size: 26rpx;
				}
				
				.clear-icon {
					display: flex;
					align-items: center;
					justify-content: center;
					width: 36rpx;
					height: 36rpx;
					border-radius: 50%;
					background-color: #f5f5f5;
					margin-left: 12rpx;
					transition: all 0.2s ease;
					
					.clear-text {
						color: #999;
						font-size: 22rpx;
						line-height: 1;
					}
					
					&:active {
						background-color: #e0e0e0;
						transform: scale(0.95);
					}
				}
			}
		}
	}
	
	.filter-bar {
		display: flex;
		background-color: #fff;
		padding: 0;
		margin: 0;
		border-radius: 0;
		width: 100%;
		
		picker {
			flex: 1;
		}
		
		.filter-item {
			width: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 44px;
			font-size: 14px;
			color: #333;
			
			text {
				margin-right: 4px;
			}
			
			.u-icon {
				color: #666;
				font-size: 12px;
			}
			
			&-disabled {
				color: #999;
			}
		}
	}
	
	.hospital-scroll {
		height: calc(100vh - 100px);
	}
	
	.hospital-item {
		display: flex;
		padding: 15px;
		background-color: #fff;
		margin-bottom: 10px;
		
		.hospital-image {
			width: 80px;
			height: 80px;
			border-radius: 4px;
			margin-right: 12px;
		}
		
		.hospital-info {
			flex: 1;
			
			.hospital-name {
				font-size: 16px;
				font-weight: bold;
				color: #333;
				margin-bottom: 6px;
			}
			
			.hospital-address {
				font-size: 14px;
				color: #666;
				margin-bottom: 6px;
			}
			
			.hospital-tags {
				margin-bottom: 6px;
				
				.tag {
					font-size: 12px;
					color: #4CD964;
					background-color: #f0f9eb;
					padding: 2px 6px;
					border-radius: 2px;
					margin-right: 6px;
				}
			}
			
			.hospital-time {
				font-size: 12px;
				color: #999;
			}
		}
		
		.hospital-actions {
			display: flex;
			align-items: center;
			padding-left: 10px;
			gap: 10px;
			
			.map-btn {
				font-size: 24rpx;
				color: #007AFF;
				background: none;
				border: none;
				padding: 8rpx 16rpx;
				margin: 0;
				white-space: nowrap;

				&:active {
					opacity: 0.7;
				}
			}
		}
	}
}
</style> 